﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace BiessesXmlReader
{
    public class Piece
    {
        public string IDesc { get;private set; }
        public string IIDesc { get;private set; }
        public double L { get;private set; }
        public double W { get;private set; }
        public int StkGrp { get;private set; }
        public int G { get;private set; }
        public int Q { get;private set; }
        public int N { get;private set; }
        List<string> Pids { get; set; }
        List<Sid> Sids { get; set; }
        public Piece()
        {
            this.Pids = new List<string>();
            this.Sids = new List<Sid>();
        }
        public static List<Piece> GetPieces(XElement x)
        {
            List<Piece> p = new List<Piece>();
            List<XElement> s = x.Elements("Piece").ToList();
            foreach (var a in s)
            {
                Piece d = new Piece();
                d.N = (a.Attribute("N") == null) ? 0 : int.Parse(a.Attribute("N").Value);
                d.L = (a.Attribute("L") == null) ? 0 : double.Parse(a.Attribute("L").Value);
                d.W = (a.Attribute("W") == null) ? 0 : double.Parse(a.Attribute("W").Value);
                d.Q = (a.Attribute("Q") == null) ? 0 : int.Parse(a.Attribute("Q").Value);
                d.G = (a.Attribute("G") == null) ? 0 : int.Parse(a.Attribute("G").Value);
                d.StkGrp = (a.Attribute("StkGrp") == null) ? 0 : int.Parse(a.Attribute("StkGrp").Value);
                d.IDesc = (a.Attribute("IDesc") == null) ? string.Empty : a.Attribute("IDesc").Value;
                d.IIDesc = (a.Attribute("IIDesc") == null) ? string.Empty : a.Attribute("IIDesc").Value;
                List<XElement> px = a.Elements("Pid").ToList();
                List<XElement> ps = a.Elements("Sid").ToList();
                foreach(var m in px)
                {
                    d.Pids.Add(m.Attribute("id")==null?string.Empty:m.Attribute("id").Value);
                }
                foreach(var m in ps)
                {
                    Sid si = new Sid();
                    si.id = (m.Attribute("id") == null) ? string.Empty : m.Attribute("id").Value;
                   List<XAttribute> xa= m.Attributes().Where(it => it.Name != "id").ToList();
                    foreach(var j in xa)
                    {
                        Pid pi = new Pid();
                        pi.id = j.Name.ToString().Substring(1);
                        pi.Qty = int.Parse(j.Value);
                        si.Pids.Add(pi);
                    }
                    d.Sids.Add(si);
                }
                p.Add(d);
            }
            return p;
        }
    }
}
